package com.lifeverse.service;

import com.lifeverse.entity.Decision;
import com.lifeverse.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 规则条件评估器
 * 负责评估规则条件是否满足
 */
@Slf4j
@Service
public class RuleConditionEvaluator {
    
    /**
     * 评估规则条件
     */
    public boolean evaluate(String conditions, Decision decision, Map<String, Object> context) {
        log.debug("评估规则条件 - 决策ID: {}", decision.getId());
        
        try {
            // 解析条件（简化实现，实际应该支持更复杂的表达式）
            Map<String, Object> conditionMap = JsonUtils.fromJson(conditions, Map.class);
            if (conditionMap == null) {
                // 如果不是JSON格式，尝试简单字符串匹配
                return evaluateSimpleCondition(conditions, decision, context);
            }
            
            return evaluateComplexCondition(conditionMap, decision, context);
            
        } catch (Exception e) {
            log.warn("规则条件评估失败: {}", conditions, e);
            return false;
        }
    }
    
    /**
     * 快速检查规则条件（用于规则筛选）
     */
    public boolean quickCheck(String conditions, Decision decision) {
        try {
            // 简化的快速检查，主要检查决策类型匹配
            if (conditions.contains("decisionType")) {
                return conditions.contains(decision.getType().name());
            }
            
            if (conditions.contains("lifeEntityType")) {
                return conditions.contains(decision.getLifeEntity().getType().name());
            }
            
            // 默认通过快速检查
            return true;
            
        } catch (Exception e) {
            log.debug("快速检查失败: {}", conditions, e);
            return false;
        }
    }
    
    /**
     * 评估简单条件
     */
    private boolean evaluateSimpleCondition(String conditions, Decision decision, Map<String, Object> context) {
        // 支持简单的条件表达式
        if (conditions.contains("energyLevel >")) {
            return evaluateEnergyCondition(conditions, decision);
        }
        
        if (conditions.contains("healthScore >")) {
            return evaluateHealthCondition(conditions, decision);
        }
        
        if (conditions.contains("wisdomScore >")) {
            return evaluateWisdomCondition(conditions, decision);
        }
        
        if (conditions.contains("decisionType ==")) {
            return evaluateDecisionTypeCondition(conditions, decision);
        }
        
        if (conditions.contains("lifeEntityType ==")) {
            return evaluateLifeEntityTypeCondition(conditions, decision);
        }
        
        // 默认条件为真
        return true;
    }
    
    /**
     * 评估复杂条件
     */
    private boolean evaluateComplexCondition(Map<String, Object> conditionMap, Decision decision, 
                                           Map<String, Object> context) {
        boolean result = true;
        
        // 评估AND条件
        if (conditionMap.containsKey("AND")) {
            result = result && evaluateAndCondition(conditionMap.get("AND"), decision, context);
        }
        
        // 评估OR条件
        if (conditionMap.containsKey("OR")) {
            result = result && evaluateOrCondition(conditionMap.get("OR"), decision, context);
        }
        
        // 评估NOT条件
        if (conditionMap.containsKey("NOT")) {
            result = result && !evaluateCondition(conditionMap.get("NOT"), decision, context);
        }
        
        // 评估具体字段条件
        for (Map.Entry<String, Object> entry : conditionMap.entrySet()) {
            String field = entry.getKey();
            Object value = entry.getValue();
            
            if (!isLogicalOperator(field)) {
                result = result && evaluateFieldCondition(field, value, decision, context);
            }
        }
        
        return result;
    }
    
    /**
     * 评估AND条件
     */
    private boolean evaluateAndCondition(Object andCondition, Decision decision, Map<String, Object> context) {
        if (andCondition instanceof java.util.List) {
            java.util.List<?> conditions = (java.util.List<?>) andCondition;
            for (Object condition : conditions) {
                if (!evaluateCondition(condition, decision, context)) {
                    return false;
                }
            }
            return true;
        }
        return evaluateCondition(andCondition, decision, context);
    }
    
    /**
     * 评估OR条件
     */
    private boolean evaluateOrCondition(Object orCondition, Decision decision, Map<String, Object> context) {
        if (orCondition instanceof java.util.List) {
            java.util.List<?> conditions = (java.util.List<?>) orCondition;
            for (Object condition : conditions) {
                if (evaluateCondition(condition, decision, context)) {
                    return true;
                }
            }
            return false;
        }
        return evaluateCondition(orCondition, decision, context);
    }
    
    /**
     * 评估单个条件
     */
    private boolean evaluateCondition(Object condition, Decision decision, Map<String, Object> context) {
        if (condition instanceof Map) {
            return evaluateComplexCondition((Map<String, Object>) condition, decision, context);
        } else if (condition instanceof String) {
            return evaluateSimpleCondition((String) condition, decision, context);
        }
        return false;
    }
    
    /**
     * 评估字段条件
     */
    private boolean evaluateFieldCondition(String field, Object value, Decision decision, Map<String, Object> context) {
        switch (field) {
            case "decisionType":
                return decision.getType().name().equals(value.toString());
            case "lifeEntityType":
                return decision.getLifeEntity().getType().name().equals(value.toString());
            case "energyLevel":
                return evaluateNumericCondition(decision.getLifeEntity().getEnergyLevel(), value);
            case "healthScore":
                return evaluateNumericCondition(decision.getLifeEntity().getHealthScore(), value);
            case "wisdomScore":
                return evaluateNumericCondition(decision.getLifeEntity().getWisdomScore(), value);
            case "creativityScore":
                return evaluateNumericCondition(decision.getLifeEntity().getCreativityScore(), value);
            case "collaborationScore":
                return evaluateNumericCondition(decision.getLifeEntity().getCollaborationScore(), value);
            case "consciousnessLevel":
                return decision.getLifeEntity().getConsciousnessLevel().name().equals(value.toString());
            default:
                // 检查上下文中的值
                if (context.containsKey(field)) {
                    return context.get(field).equals(value);
                }
                return false;
        }
    }
    
    /**
     * 评估数值条件
     */
    private boolean evaluateNumericCondition(BigDecimal actualValue, Object conditionValue) {
        if (conditionValue instanceof Map) {
            Map<String, Object> condition = (Map<String, Object>) conditionValue;
            
            if (condition.containsKey("gt")) {
                BigDecimal threshold = new BigDecimal(condition.get("gt").toString());
                return actualValue.compareTo(threshold) > 0;
            }
            
            if (condition.containsKey("gte")) {
                BigDecimal threshold = new BigDecimal(condition.get("gte").toString());
                return actualValue.compareTo(threshold) >= 0;
            }
            
            if (condition.containsKey("lt")) {
                BigDecimal threshold = new BigDecimal(condition.get("lt").toString());
                return actualValue.compareTo(threshold) < 0;
            }
            
            if (condition.containsKey("lte")) {
                BigDecimal threshold = new BigDecimal(condition.get("lte").toString());
                return actualValue.compareTo(threshold) <= 0;
            }
            
            if (condition.containsKey("eq")) {
                BigDecimal threshold = new BigDecimal(condition.get("eq").toString());
                return actualValue.compareTo(threshold) == 0;
            }
            
            if (condition.containsKey("between")) {
                java.util.List<?> range = (java.util.List<?>) condition.get("between");
                if (range.size() == 2) {
                    BigDecimal min = new BigDecimal(range.get(0).toString());
                    BigDecimal max = new BigDecimal(range.get(1).toString());
                    return actualValue.compareTo(min) >= 0 && actualValue.compareTo(max) <= 0;
                }
            }
        } else {
            // 直接比较相等
            BigDecimal threshold = new BigDecimal(conditionValue.toString());
            return actualValue.compareTo(threshold) == 0;
        }
        
        return false;
    }
    
    /**
     * 评估能量条件
     */
    private boolean evaluateEnergyCondition(String conditions, Decision decision) {
        try {
            String[] parts = conditions.split(">");
            if (parts.length == 2) {
                BigDecimal threshold = new BigDecimal(parts[1].trim());
                return decision.getLifeEntity().getEnergyLevel().compareTo(threshold) > 0;
            }
        } catch (Exception e) {
            log.debug("解析能量条件失败: {}", conditions, e);
        }
        return false;
    }
    
    /**
     * 评估健康条件
     */
    private boolean evaluateHealthCondition(String conditions, Decision decision) {
        try {
            String[] parts = conditions.split(">");
            if (parts.length == 2) {
                BigDecimal threshold = new BigDecimal(parts[1].trim());
                return decision.getLifeEntity().getHealthScore().compareTo(threshold) > 0;
            }
        } catch (Exception e) {
            log.debug("解析健康条件失败: {}", conditions, e);
        }
        return false;
    }
    
    /**
     * 评估智慧条件
     */
    private boolean evaluateWisdomCondition(String conditions, Decision decision) {
        try {
            String[] parts = conditions.split(">");
            if (parts.length == 2) {
                BigDecimal threshold = new BigDecimal(parts[1].trim());
                return decision.getLifeEntity().getWisdomScore().compareTo(threshold) > 0;
            }
        } catch (Exception e) {
            log.debug("解析智慧条件失败: {}", conditions, e);
        }
        return false;
    }
    
    /**
     * 评估决策类型条件
     */
    private boolean evaluateDecisionTypeCondition(String conditions, Decision decision) {
        try {
            String[] parts = conditions.split("==");
            if (parts.length == 2) {
                String expectedType = parts[1].trim().replace("\"", "");
                return decision.getType().name().equals(expectedType);
            }
        } catch (Exception e) {
            log.debug("解析决策类型条件失败: {}", conditions, e);
        }
        return false;
    }
    
    /**
     * 评估生命体类型条件
     */
    private boolean evaluateLifeEntityTypeCondition(String conditions, Decision decision) {
        try {
            String[] parts = conditions.split("==");
            if (parts.length == 2) {
                String expectedType = parts[1].trim().replace("\"", "");
                return decision.getLifeEntity().getType().name().equals(expectedType);
            }
        } catch (Exception e) {
            log.debug("解析生命体类型条件失败: {}", conditions, e);
        }
        return false;
    }
    
    /**
     * 判断是否为逻辑操作符
     */
    private boolean isLogicalOperator(String field) {
        return "AND".equals(field) || "OR".equals(field) || "NOT".equals(field);
    }
}